import { Paho } from "ng2-mqtt/mqttws31";
import mqttConst from "./mqttConst";
class mqttTool{
    //连接方法
    public static MqttConnect(option){
        if(!option){
            option = {
                timeout: 3,
                useSSL: false,
                cleanSession: true,
                keepAliveInterval:10,
                userName:mqttConst.mqttConfig.username,
                password:mqttConst.mqttConfig.password,
                onSuccess:mqttTool.onConnect,
                onFailure: function (message) {
                    //每个1s重连一次
                    if(mqttConst.reTime < 3){
                        mqttConst.reTime ++ ;
                        mqttTool.MqttConnect(null);
                    }else{
                        //大于三次连接失败，不再重连，提示用户
                        mqttConst.reTime = 0;
                        alert("MQTT服务器连接失败，请检查网络！");
                    }
                }
            }
        }
        //建立客户端实例
        mqttConst.client = new Paho.MQTT.Client(mqttConst.mqttConfig.mqhost, mqttConst.mqttConfig.mqport,"/ws", "web_" + parseInt(Math.random() * 100+"", 10));
        mqttConst.client.connect(option);
    }
    //主题订阅
    public static onConnect() {
        console.log("-----------mqtt连接服务器成功！------------");
        //订阅主题
        mqttConst.client.subscribe(mqttConst.topic,{});
        //console.log("订阅主题："+mqttConst.topic+"成功！");
        //连接成功，重连次数清0
        mqttConst.reTime = 0;
    }
    //失去连接
    private onConnectionLost(responseObject) {
        if (responseObject.errorCode !== 0) {
            console.log("onConnectionLost:"+responseObject.errorMessage);
            if(mqttConst.reTime < 3){
                mqttConst.reTime ++ ;
                mqttTool.MqttConnect(null);
            }else{
                //大于三次连接失败，不再重连，提示用户
                mqttConst.reTime = 0;
                alert("MQTT服务器连接失败，请检查网络！");
            }
        }
    }
    //消息到达
    public static onMessageArrived(message) {
        //收到消息
        console.log("重连获取到的消息："+JSON.stringify(message));
        return message;
    }
    //重连机制
    private reConnect(){
        //每个1s重连一次
        if(mqttConst.reTime < 3){
            mqttConst.reTime ++ ;
            mqttTool.MqttConnect(null);
           // setTimeout(mqttTool.MqttConnect, SysData.mqttConfig.reconnectTimeout);
        }else{
            //大于三次连接失败，不再重连，提示用户
            mqttConst.reTime = 0;
            alert("MQTT服务器连接失败，请检查网络！");
        }
    }
    //连接mqtt,内部调用
    private listenMqtt(topic,callback1,callback2){
        mqttConst.topic = topic;
       /*  if(!mqttConst.client || !mqttConst.client.isConnected()){
            let nowConnTime = new Date().getTime()+"";
            if(!mqttConst.lastConnTime || mqttConst.lastConnTime!= nowConnTime){
                mqttConst.reTime = 0;
                mqttConst.lastConnTime = nowConnTime;
            }
            mqttTool.MqttConnect(null);
        } */
        let nowConnTime = new Date().getTime()+"";
        if(!mqttConst.lastConnTime || mqttConst.lastConnTime!= nowConnTime){
            mqttConst.reTime = 0;
            mqttConst.lastConnTime = nowConnTime;
        }
        mqttTool.MqttConnect(null);
        mqttConst.client.onMessageArrived = callback1;//注册消息接收处理事件
        mqttConst.client.onConnectionLost = callback2;//this.onConnectionLost;//注册连接断开处理事件
       
    }
    /* 
        提供给外部调用
        currCompnet:当前监听mqtt消息的component，传this
        topic:订阅主题
    */
    public listenMqttMessage(currCompnet,topic){
        let msg=0;
        this.stopMqttConn();
        mqttConst.currMqttTool = this;
        mqttConst.currThis = currCompnet;
        this.listenMqtt(topic,function(message:Paho.MQTT.Message){
            msg++;
            mqttConst.currThis.dealMqttMsg(message.payloadString);
        },function(responseObject){
          if (responseObject.errorCode !== 0) {
            if(mqttConst.reTime < 3){
                mqttConst.reTime ++ ;
                console.log("-----------mqtt与服务器断开连接，正在尝试第["+mqttConst.reTime+"]次重连...");         
                mqttConst.currMqttTool.listenMqttMessage(mqttConst.currThis,mqttConst.topic);   
                setTimeout(()=>{
                    if(msg==0 && topic!=='EAS_ANT_STATUS_CHG'){
                        mqttConst.currThis.dealOverTime();
                    }
                },mqttConst.mqttConfig.reconnectTimeout);  
            }else{
                //大于三次连接失败，不再重连，提示用户
                mqttConst.reTime = 0;
                alert("MQTT服务器连接失败，请检查网络！");
            }
          }
        });
      }
      //关闭mqtt连接
    public stopMqttConn(){
        if(mqttConst.client && mqttConst.client.isConnected()){
            mqttConst.client.unsubscribe(mqttConst.topic,{});
            mqttConst.client.disconnect();
            mqttConst.client = null;
            mqttConst.reTime = 0;
            mqttConst.lastConnTime = "";
            console.log("MQTT--客户端主动断开连接-----");
        }
    }
}
export default new mqttTool();